import Layout from '@/layout/index.vue'

// 定义组件映射，以便Vite可以静态分析动态导入
const componentMap: Record<string, () => Promise<any>> = {
  'dashboard/index': () => import('@/views/dashboard/index.vue'),
  'system/user/index': () => import('@/views/system/user/index.vue'),
  'system/role/index': () => import('@/views/system/role/index.vue'),
  'system/menu/index': () => import('@/views/system/menu/index.vue'),
  'system/dept/index': () => import('@/views/system/dept/index.vue'),
  'server/list/index': () => import('@/views/server/list/index.vue'),
  'server/monitor/index': () => import('@/views/server/monitor/index.vue'),
  'system/log/index': () => import('@/views/system/logView/index.vue'),
  'login/index': () => import('@/views/login/index.vue'),
  'profile/index': () => import('@/views/profile/index.vue'),
  // 根据需要添加其他组件映射
}

export function menuToRoutes(menuList: any[], parentPath = ''): any[] {
  const routes: any[] = []
  menuList.forEach(menu => {
    // 拼接完整 path
    let fullPath = menu.path
    if (!fullPath.startsWith('/')) {
      fullPath = parentPath ? `${parentPath}/${menu.path}` : `/${menu.path}`
    }
    // 目录类型
    if (menu.type === 'M') {
      routes.push({
        path: fullPath,
        component: Layout,
        meta: { title: menu.name, icon: menu.icon },
        children: menuToRoutes(menu.children || [], fullPath)
      })
    }
    // 菜单类型
    else if (menu.type === 'C') {
      const componentLoader = componentMap[menu.component];
      if (componentLoader) {
        routes.push({
          path: fullPath,
          name: menu.name,
          component: componentLoader, // 使用预定义的loader
          meta: { title: menu.name, icon: menu.icon }
        })
      } else {
        console.warn(`Component not found in map for path: ${menu.component}`);
      }
    }
  })
  return routes
}
